<template>
  <Row ref="el" class="je-admin-top-menus" :justify="menuStore.topMenuAlign">
    <Col
      v-for="menu in menus"
      v-show="menus.length > 1"
      :key="menu.id"
      :class="{
        'menu-item': true,
        'menu-empty': menu.empty,
        'menu-item-selected': menu.id === menuStore.activeTopMenu,
      }"
      @click="onTopMenuOpen(menu)"
    >
      <i :class="['menu-item-icon', menu.icon]" />{{ menu.text }}
    </Col>
  </Row>
</template>
<script>
  import { defineComponent, computed, ref, onMounted, nextTick } from 'vue';
  import { Row, Col } from '@jecloud/ui';
  import { useMenuStore } from '@/stores/menu-store';
  import { openTopMenu } from '@/hooks/use-menu';
  export default defineComponent({
    name: 'AdminTopMenus',
    components: { Row, Col },
    setup(props, context) {
      const menuStore = useMenuStore();
      const el = ref();
      // 顶部菜单数据
      const menus = computed(() => {
        return menuStore.init
          ? menuStore.getTopMenus()
          : [1, 2, 3].map((id) => ({
              empty: true,
              id,
            }));
      });
      // 打开顶部菜单
      const onTopMenuOpen = (menu) => {
        menuStore.openAction = 'topMenuClick';
        openTopMenu(menu);
        nextTick(() => {
          menuStore.openAction = '';
        });
      };

      onMounted(() => {
        nextTick(() => {
          const childirn = Array.from(el.value.$el.children);
          let width = 0;
          childirn.forEach((dom) => {
            width += dom.offsetWidth;
          });
          el.value.$el.style.minWidth = width + 'px';
        });
      });
      return { menuStore, menus, onTopMenuOpen, el };
    },
  });
</script>
<style lang="less">
  .je-admin-top-menus {
    flex-wrap: nowrap !important;
    .menu-item {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      padding: 0 25px;
      flex: none;
      cursor: pointer;

      &-icon {
        margin-right: 10px;
        font-size: 20px;
      }
    }
  }
</style>
